// price.ts
Page({
  data: {
    fuelPrices: [
      { type: '92', name: '92号汽油', price: '7.85' },
      { type: '95', name: '95号汽油', price: '8.35' },
      { type: '98', name: '98号汽油', price: '9.15' },
      { type: 'diesel', name: '0号柴油', price: '7.25' }
    ],
    editingIndex: -1,
    tempPrice: ''
  },

  onLoad() {
    this.loadPrices()
  },

  loadPrices() {
    const storedPrices = wx.getStorageSync('fuelPrices')
    if (storedPrices && storedPrices.length > 0) {
      this.setData({
        fuelPrices: storedPrices
      })
    }
  },

  startEdit(e: any) {
    const index = e.currentTarget.dataset.index
    const currentPrice = this.data.fuelPrices[index].price
    
    this.setData({
      editingIndex: index,
      tempPrice: currentPrice
    })
  },

  onPriceInput(e: any) {
    this.setData({
      tempPrice: e.detail.value
    })
  },

  savePrice() {
    const { editingIndex, tempPrice, fuelPrices } = this.data
    
    if (!tempPrice || isNaN(parseFloat(tempPrice))) {
      wx.showToast({
        title: '请输入有效价格',
        icon: 'error'
      })
      return
    }

    const price = parseFloat(tempPrice).toFixed(2)
    const updatedPrices = [...fuelPrices]
    updatedPrices[editingIndex].price = price

    this.setData({
      fuelPrices: updatedPrices,
      editingIndex: -1,
      tempPrice: ''
    })

    // 保存到本地存储
    wx.setStorageSync('fuelPrices', updatedPrices)
    
    wx.showToast({
      title: '价格更新成功',
      icon: 'success'
    })
  },

  cancelEdit() {
    this.setData({
      editingIndex: -1,
      tempPrice: ''
    })
  },

  batchUpdate() {
    wx.showModal({
      title: '批量调价',
      content: '确定要执行批量调价操作吗？',
      success: (res) => {
        if (res.confirm) {
          // 这里可以实现批量调价逻辑
          wx.showToast({
            title: '批量调价功能开发中',
            icon: 'none'
          })
        }
      }
    })
  },

  resetPrices() {
    wx.showModal({
      title: '重置价格',
      content: '确定要重置为默认价格吗？',
      success: (res) => {
        if (res.confirm) {
          const defaultPrices = [
            { type: '92', name: '92号汽油', price: '7.85' },
            { type: '95', name: '95号汽油', price: '8.35' },
            { type: '98', name: '98号汽油', price: '9.15' },
            { type: 'diesel', name: '0号柴油', price: '7.25' }
          ]
          
          this.setData({
            fuelPrices: defaultPrices,
            editingIndex: -1,
            tempPrice: ''
          })
          
          wx.setStorageSync('fuelPrices', defaultPrices)
          
          wx.showToast({
            title: '价格已重置',
            icon: 'success'
          })
        }
      }
    })
  }
})